package cn.mw.cmdb.timeplan.entity;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.mw.cmdb.entity.PropertyTypeString;
import cn.mw.cmdb.entity.PropertyTypeTime;
import cn.mw.cmdb.timeplan.enums.MwTimePlanTypeEnum;
import cn.mw.cmdb.timeplan.param.MwTimePlanParam;
import cn.mw.components.mongodb.anno.AutoId;
import cn.mw.components.mongodb.anno.CMDBProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Data
@Document("mw_cmdbmd_timeplan")
public class MwTimePlan {
    private static final String TimeSep = ":";

    @Schema(description = "时间计划Id")
    @CMDBProperty(searchType = PropertyTypeString.ID)
    @AutoId
    private String id;

    @Schema(description = "名称")
    @CMDBProperty(searchType = PropertyTypeString.ID ,keywordSearch = true)
    private String name;

    @Schema(description = "类型")
    @CMDBProperty(searchType = PropertyTypeString.ID)
    private String type;

    @Schema(description = "生效时间类型")
    @CMDBProperty(searchType = PropertyTypeString.ID)
    private String activeTimeType;

    @Schema(description = "生效开始时间")
    @CMDBProperty(searchType = PropertyTypeTime.ID)
    private Date activeSince;

    @Schema(description = "生效结束时间")
    @CMDBProperty(searchType = PropertyTypeTime.ID)
    private Date activeTill;

    @Schema(description = "每日")
    private List<Integer> dayParam;

    @Schema(description = "每周")
    private MwTimePlanWeek weekParam;

    @Schema(description = "每月")
    private MwTimePlanMonth monthParam;

    @Schema(description = "执行时间")
    @CMDBProperty(searchType = PropertyTypeString.ID)
    private String executeTime;

    @Schema(description = "定时表达式")
    private List<String> crons;

    @Schema(description = "维护时间段")
    private List<MaintainTime> maintainTimes;

    @Schema(description = "描述")
    private String describe;

    public List<String> readCustomTime(){
        if(null != activeSince && null != activeTill){
            List<String> ret = new ArrayList<>();
            ret.add(DateUtil.format(activeSince ,MwTimePlanParam.TimeFormate));
            ret.add(DateUtil.format(activeTill ,MwTimePlanParam.TimeFormate));
            return ret;
        }

        return null;
    }

    public void init() throws ParseException {
        boolean isSet = false;
        String[] cronArr = new String[]{"0" ,"0" ,"0" ,"0" ,"0" ,"0"};
        List<String> weekOfMonths = null;
        if(!StringUtils.hasText(executeTime)){
            return;
        }

        String[] times = executeTime.split(TimeSep);
        cronArr[1] = Integer.toString(NumberUtil.parseInt(times[1]));
        cronArr[2] = Integer.toString(NumberUtil.parseInt(times[0]));

        if(!StringUtils.isEmpty(type) && type.equals(MwTimePlanTypeEnum.DAY.getType())){
            if(null != dayParam ){
                cronArr[3] = StringUtils.collectionToCommaDelimitedString(dayParam);
            }else{
                cronArr[3] = "*";
            }
            cronArr[4] = "*";
            cronArr[5] = "?";
            isSet = true;
        }

        if(!StringUtils.isEmpty(type) && type.equals(MwTimePlanTypeEnum.WEEK.getType())){
            if(null != weekParam && CollectionUtils.isNotEmpty(weekParam.getWeekIndexes())){
                String dayOfWeek = StringUtils.collectionToCommaDelimitedString(weekParam.getWeekIndexes());
                cronArr[5] = dayOfWeek;
            }else{
                cronArr[5] = "*";
            }
            cronArr[3] = "?";
            cronArr[4] = "*";
            isSet = true;
        }

        if(!StringUtils.isEmpty(type) && type.equals(MwTimePlanTypeEnum.MONTH.getType())){
            if(null != monthParam){
                if(monthParam.getMonthIndexes() != null){
                    cronArr[4] = StringUtils.collectionToCommaDelimitedString(monthParam.getMonthIndexes());
                }else{
                    cronArr[4] = "*";
                }
                if(null != monthParam.getDayIndexes()){
                    cronArr[3] = StringUtils.collectionToCommaDelimitedString(monthParam.getDayIndexes());
                    cronArr[5] = "?";
                    isSet = true;
                }

                if(null != monthParam.getWeekIndexPerMonth()){
                    cronArr[3] = "?";

                    weekOfMonths = new ArrayList<>();
                    for(int weekIndex:monthParam.getWeekIndexes()){
                        for(int weekIndexPerMonth : monthParam.getWeekIndexPerMonth()){
                            String str = weekIndex + "#" + weekIndexPerMonth;
                            weekOfMonths.add(str);
                        }
                    }
                    isSet = true;
                }
            }
        }


        if(type != null && type.equals(MwTimePlanTypeEnum.ONCE.getType())){
            //通过执行时间直接生成corn表达式
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date date = format.parse(executeTime);
            format.applyPattern("ss mm HH dd MM ? yyyy");
            String cron = format.format(date);
            crons = Arrays.asList(cron);
        }

        if(isSet){
            crons = new ArrayList<>();
            if(null != weekOfMonths){
                for(String str : weekOfMonths){
                    String[] temp = Arrays.copyOf(cronArr ,6);
                    temp[5] = str;
                    crons.add(StringUtils.collectionToDelimitedString(Arrays.asList(temp) ," "));
                }
            }else{
                crons.add(StringUtils.collectionToDelimitedString(Arrays.asList(cronArr), " "));
            }
        }
    }
}
